﻿using System.IO;
using ServiceStack.Text;

namespace Mnk.Merger.Code.Common
{
    class JsonDataSerializer : IJsonDataSerializer
    {
        public T Load<T>(string path, T defValue = default(T)) where T : class
        {
            if (File.Exists(path))
            {
                using (var s = File.Open(path, FileMode.Open))
                {
                    return JsonSerializer.DeserializeFromStream<T>(s) ?? defValue;
                }
            }
            if (defValue != null) Save(path, defValue);
            return defValue;
        }

        public void Save<T>(string path, T data) where T : class
        {
            using (var s = File.Open(path, FileMode.Create))
            {
                JsonSerializer.SerializeToStream(data, s);
            }
        }
    }
}